import _ from 'underscore'
import $ from 'jquery'
import dispatcher from 'lib/dispatcher'
import TimeStore from 'lib/stores/time-store'
import {Scope} from 'lib/scopeFactory'
// import {imsiApi,createGridOrder,parseToPartIMSIGrid} from '../apis/imsi-grid-util'
import {tracelistApi,createGridOrder,gridSortScendFn} from '../apis/tracelist'
export default class UserListScope extends Scope {
  constructor(props){
    super(props);
    // console.log('props',props);
    // console.log('props.routeParams',props.routeParams);
    if (props.routeParams.userIdentifier) {
      this.userId = decodeURIComponent(props.routeParams.userIdentifier);
    }
    this.$state = {
      // showUserList:!!this.userId,
      grid:{
        loading:true,
        getOrder:createGridOrder('timestamp',-1), //排序字段 appVersion（app版本），timestamp(采集时间)
        fetch:this.fetchGrid.bind(this)
      }
    }
    this.imsiApiParams = {
      urlName:'custom/userinfos',
      limit:20,
      //userIdentifier:this.userId,
      dataType:0
    }
    if (this.userId) {
      this.imsiApiParams = _.extend(this.imsiApiParams,{
        userIdentifier:this.userId
      })
    }
    this.imsiApi = tracelistApi(this.imsiApiParams,
                                TimeStore.getValue,
                                this.$state.grid.getOrder)
  }
  fetchGrid(){
    var _this = this
    // if (this.userId) {
      this.imsiApi.fetch().then((rawData,params) => {
        // _this.$state.grid = parseToPartGrid(rawData,params)
        var sortOption = gridSortScendFn(params.order)
        _this.$state.grid = {
          data:rawData,
          sortKey:sortOption.key,
          sortScend:sortOption.scend,
          hasMore:false,
          showMore:function(){
            return tracelistApi(params,{
              offset:this.data.length
            }).fetch().then(function(innerData, innerParams) {
              if (callback) {
                callback(innerData);
              }
              return {
                data:innerData,
                hasMore:innerData.length === innerParams.limit
              }
            })
          }
        }
        // _this.$state.grid = parseToPartIMSIGrid(rawData,params)
        // _this.$state.grid = parseToPartIMSIGrid(rawData.data,params)
        _this.emit()
      })
    // }
  }
  $settime(){
    this.fetchGrid()
  }
  $load(){
    this.fetchGrid()
  }
}
